package com.grao.waterschool.human.manager.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import cn.hutool.core.util.StrUtil;
import com.grao.waterschool.human.utils.Base64MultipartFile;
import com.grao.waterschool.human.utils.EmptyUtils;
import com.grao.waterschool.human.entiry.po.Files;
import com.grao.waterschool.human.manager.service.FileUploadService;
import com.grao.waterschool.human.mapper.FilesMapper;
import com.grao.waterschool.human.utils.MinioUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Base64;


/**
 * 图片文件上传
 */

@Slf4j
@Service
public class FileUploadServiceImpl implements FileUploadService {

    @Value("${minio.userImagesBucket}")
    private String bucketName;

    @Autowired
    private FilesMapper filesMapper;

    @Autowired
    MinioUtil minioUtil;

    private static String FileName() {
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy_MM_dd_HH_mm_ss");
        return now.format(formatter) + "_test"; // 这里不再硬编码文件扩展名，因为它将在上传时根据实际类型确定
    }

    @Override
    public SaResult uploadFiles(String fileForBase64) throws Exception {
        if (!StpUtil.isLogin()) {
            return SaResult.error("请先登录");
        }

        MultipartFile file = null;
        if (StrUtil.isNotBlank(fileForBase64)) {
            // 分离Base64数据前缀
            String[] baseStrs = fileForBase64.split(",");
            if (baseStrs.length == 2) {
                byte[] decodedBytes = Base64.getDecoder().decode(baseStrs[1]);
                file = new Base64MultipartFile(decodedBytes, baseStrs[0]);
            } else {
                return SaResult.error("Base64数据格式不正确");
            }
        }

        if (file == null || EmptyUtils.basicIsEmpty(file.getOriginalFilename())) {
            return SaResult.error("文件名不能为空");
        }

        String fileName = file.getOriginalFilename();
        String originalFileType = FilenameUtils.getExtension(fileName).toLowerCase();
        String suffixName = FileName();

        try (InputStream inputStream = file.getInputStream()) {
            minioUtil.uploadFile(inputStream, bucketName, suffixName + "." + originalFileType);
        } catch (IOException e) {
            log.error("文件上传到MinIO失败", e);
            return SaResult.error("文件上传失败");
        } catch (IllegalArgumentException e) {
            log.error("流为空", e);
            return SaResult.error("流为空");
        }

        Files files = new Files()
                .setFilePath(suffixName + "." + originalFileType)
                .setFileName(fileName)
                .setUserId(StpUtil.getLoginIdAsString())
                .setSuffix(originalFileType);
//        filesMapper.insert(files);
        return SaResult.get(200, "上传成功", suffixName + "." + originalFileType);
    }
}
